var Adminer = function(){

	var hanlderForm = function(){
		var form1 = $('#user_add_form');
		form1.validate({
			errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            ignore: "",
            rules: {
                'partner[]': {
                    required: true
                },
                'game[]': {
                    required: true
                },
                'channel[]': {
                    required: true
                },
                username: {
                    required: true,
                    maxlength:20
                },
                nickname: {
                    maxlength:20
                },
                password:{
                	required: true,
                    maxlength:20,
                    minlength:6
                }
                
            },
             errorPlacement: function (error, element) { // render error placement for each input type
                if (element.parent(".input-group").size() > 0) {
                    error.insertAfter(element.parent(".input-group"));
                } else if (element.attr("data-error-container")) { 
                    error.appendTo(element.attr("data-error-container"));
                } else if (element.parents('.radio-list').size() > 0) { 
                    error.appendTo(element.parents('.radio-list').attr("data-error-container"));
                } else if (element.parents('.radio-inline').size() > 0) { 
                    error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
                } else if (element.parents('.checkbox-list').size() > 0) {
                    error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
                } else if (element.parents('.checkbox-inline').size() > 0) { 
                    error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
                } else {
                    error.insertAfter(element); // for other inputs, just perform default behavior
                }
            },

            invalidHandler: function (event, validator) { //display error alert on form submit 
               // App.scrollTo(error1, -200);
            },

            highlight: function (element) { // hightlight error inputs
                $(element)
                    .closest('.form-group').addClass('has-error'); // set error class to the control group
            },

            unhighlight: function (element) { // revert the change done by hightlight
                $(element)
                    .closest('.form-group').removeClass('has-error'); // set error class to the control group
            },

            success: function (label) {
                label
                    .closest('.form-group').removeClass('has-error'); // set success class to the control group
            },

            submitHandler: function (form) {
				// Post-submit callback 
				function showResponse (responseText, statusText) { 
					if(responseText.code==0) {
						toastr.success("添加成功！");
						window.location.href ="user/adminers";
					} else {
						toastr.error(responseText.msg);
					}
				} 

            	var options = {
            		type:"post",
			        url:"user/adminer_insert",
			        dataType:'json',
						 success:       showResponse, 
            	}

        		form1.ajaxSubmit(options);
	   		                    
            }
		});
	}

	return {
	    init: function () {

	    	hanlderForm();

	    	$("#username,#nickname,#group").editable({
				url: 'user/adminer_update',
				ajaxOptions: {
			        dataType: 'json'
			    },
				success:function(response,newValue){
					console.log(response);
					if(response.code==1) 
					{return response.msg;} 
				}
			});


	    	//动态生成channel
	    	function get_channel()
	    	{
	    		//获取所有选中的partner
	    		var partner = get_checked_value('partner[]');
	    		var game = get_checked_value('game[]');
	    		if( partner || game)
	    		{
	    			$.ajax({
	    				url: 'server/ajax_channels',
	    				type: 'POST',
	    				dataType: 'json',
	    				data: {partner: partner,game:game},
	    			})
	    			.done(function(responseText) {
	    				var chkList = $('#channel_checkbox_list').children('.checkbox-inline').not(':first').remove();
	    				//chkList.empty();

	    				//var chkAll = '<label class="checkbox-inline"><input type="checkbox" id="" value="" class="checkall"> 全选 </label>';
	    				//chkList.append(chkAll);
	    				$.each(responseText, function(index, val) {
	    					var chk = '<label class="checkbox-inline"><input type="checkbox" class="checkboxes" name="channel[]" value="'+val.channel_id+'" class="checkboxes">'+val.channel_name+'</label>';
	    					//chkList.append(chk);
	    					$(chk).insertAfter($('#channel_checkbox_list').children('.checkbox-inline').eq(0));
	    				});

	    				$('#channel_checkbox_list .checkboxes').uniform()	
	    			})
	    			.fail(function() {
	    				console.log("error");
	    			})
	    			.always(function() {
	    				console.log("complete");
	    			});
	    			
	    		}
	    	}

	    	//全选事件
	    	$('.checkall').on('change',function(){
	    		var checked = jQuery(this).is(":checked");
	    		$(this).parents('.checkbox-list').find('.checkboxes').each(function(index,el) {
	    			$.uniform.update($(el).attr("checked", checked));
	    		});
	    		if($(this).parents('.checkbox-list').attr('id') !== 'channel_checkbox_list') {
	    			get_channel();
	    		}
	    	});	

	    	$('.checkboxes').on('change',function(){
	    		get_channel();
	    	});

	    	function get_checked_value(element)
	    	{
	    		var value = '';
	    		$('input[name="'+element+'"]:checked').each(function(index, el) {
	    	   	   value += el.value+',';
	    	   });
	    	   return value;
	    	}	

	    	//删除用户
	    	$(document).on('click','.adminer_delete_btn',function(){
	    		var id = $(this).attr('data-pk');
	    		var tr = $(this).parents('tr');
	    		bootbox.confirm("确认删除用户？", function(result) {
	    			if(result)
	    			{
	    				$.ajax({
			    			url: 'user/adminer_delete',
			    			type: 'POST',
			    			dataType: 'json',
			    			data: {id: id},
			    		})
			    		.done(function(response) {
			    			if(response.code==0)
			    			{
			    				toastr.success(response.msg);
			    				tr.remove();
			    			} else
			    			{
			    				toastr.error(response.msg);
			    			}
			    		})
			    		.fail(function() {
			    			console.log("error");
			    		})
			    		.always(function() {
			    			console.log("complete");
			    		});
	    			}			   	    		
	    		});		    	
			});

			//重置密码
			$(document).on('click','.reset_pwd_btn',function(){
	    		var name = $(this).attr('data-pk');
	    		if(name) {
		    		bootbox.prompt("请输入新密码", function(result) {
		    			if(result)
		    			{
		    				$.ajax({
				    			url: 'user/adminer_reset_pwd',
				    			type: 'POST',
				    			dataType: 'json',
				    			data: {name: name,password:result},
				    		})
				    		.done(function(response) {
				    			if(response.code==0)
				    			{
				    				toastr.success(response.msg);
				    				tr.remove();
				    			} else
				    			{
				    				toastr.error(response.msg);
				    			}
				    		})
				    		.fail(function() {
				    			console.log("error");
				    		})
				    		.always(function() {
				    			console.log("complete");
				    		});
		    			}			   	    		
		    		});
	    		}		    	
			});
		}
	};
}();   